<?php

namespace App\Models\Chanjet;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class TplusToken extends Model
{
    protected $table = 'tplus_token';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];
    public static function saveTplusToken($data = []){
        if(empty($data) || !isset($data['org_id'])) return false;
        $info = self::where('org_id',$data['org_id'])->first();
        $base_data = [
            'access_token' => $data['access_token'],
            'refresh_token' => $data['refresh_token'],
            'expires_in' => $data['expires_in'],
            'res' => json_encode($data),
        ];
        if($info){
            $base_data['update_at'] = time();
            //影响行数
            $res = self::where([
                'org_id' => $data['org_id'],
            ])->update($base_data);
        }else{
            //获取自增id
            $base_data['create_at'] = time();
            $base_data['update_at'] = time();
            $base_data['org_id']    = $data['org_id'];
            $base_data['user_id']   = $data['user_id'];
            $res = self::insertGetId($base_data);
        }

        if($res > 0){
            return $data['access_token'];
        }else{
            return false;
        }
    }

}
